<template>
	<view style="" v-if="formData.title">
		<view>
			<image :src="formData.photo_url" style="height: 300rpx;width: 100%;" mode="aspectFill"></image>
		</view>
		<view class="box">
			<view class="title">{{formData.title}}</view>
			<view class="item">
				<view class="titles">地点:</view>
				<view class="values" style="color:#2979ff" @click="toMap">{{formData.address}}{{formData.detailAddress}}
				</view>
			</view>
			<view class="item">
				<view class="titles">开始时间：</view>
				<view class="values">{{formData.create_time}}</view>
			</view>
			<view class="item">
				<view class="titles">截止时间：</view>
				<view class="values">{{formData.end_time}}</view>
			</view>
			<view class="item">
				<view class="titles">名额限制：</view>
				<view class="values">{{formData.enrollment}}/{{formData.peopleNum}}</view>
			</view>
			<view class="item">
				<view class="titles">基础费用：</view>
				<view class="values">￥{{parseFloat(formData.basicrate).toFixed(2)}}</view>
			</view>
		</view>
		<view class="line"></view>
		<view class="checkx">
			<view class="title" style="font-size: 30rpx;">其他报名费用<text
					style="font-size: 26rpx;color: #c8c9cc;margin-left: 6rpx;font-weight: normal;">(可多选)</text></view>
			<view class="checkeds">
				<uv-checkbox-group v-if="formData.otherArr.length > 0" @change="changeGroup" v-model="checkboxValue"
					placement="column" iconPlacement="right">
					<uv-checkbox :customStyle="{marginBottom: '8px'}" v-for="(item, index) in formData.otherArr"
						:key="index" :label="item.text" :name="item.value">
						<view style="display: flex;align-items: center;">
							{{item.text}}
							<view
								style="margin-left: 10rpx;color: #fa3534;font-weight: bold;font-style: italic;font-size: 28rpx;">
								￥{{parseFloat(item.price).toFixed(2) }}</view>
						</view>
					</uv-checkbox>
				</uv-checkbox-group>
				<view v-else style="text-align: center;">
					<uv-empty mode="data" text="暂无其他费用" icon="https://cdn.uviewui.com/uview/empty/data.png"></uv-empty>
				</view>
			</view>
		</view>
		<view class="line"></view>
		<view class="boxs" style="padding-bottom: 160rpx;">
			<view class="title" style="font-size: 30rpx;">比赛规则</view>
			<view class="infos">
				<uv-parse :content="formData.capRule"></uv-parse>
			</view>
		</view>
		<view class="footer">
			<view class="left">
				<view class="phones">
					<uv-icon name="phone" color="#000000" @click="callPhone" size="23"></uv-icon>
				</view>
			</view>
			<view class="right">
				合计：<view style="color: #fa3534;font-weight: bold;font-style: italic;font-size: 32rpx;">
					￥{{parseFloat(total).toFixed(2) }}</view>
			</view>
			<view class="center" v-if="!isOut">
				<view v-if="Number(formData.peopleNum) != formData.enrollment" class="btn"
					:style="{backgroundColor:findIndex == '-1' ?  '#ff9900' : '#f9d39b'}" @click="pay">
					{{findIndex == '-1' ? '立即报名':'已报名'}}
				</view>
				<view v-else class="btn">报名人数上限</view>
			</view>
			<view class="center" v-else>
				<view class="btn" style="background-color: #f9d39b;">报名已截止</view>
			</view>
		</view>
		<uni-pay ref="pay" @success="onSuccess" @create="onCreate" @fail="onFail"></uni-pay>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				total_fee: 1, // 支付金额，单位分 100 = 1元
				order_no: "", // 业务系统订单号（即你自己业务系统的订单表的订单号）
				out_trade_no: "", // 插件支付单号
				qr_code: false, // 是否强制使用扫码支付
				description: "测试订单", // 支付描述
				type: "goods", // 支付回调类型 如 recharge 代表余额充值 goods 代表商品订单（可自定义，任意英文单词都可以，只要你在 uni-pay-co/notify/目录下创建对应的 xxx.js文件进行编写对应的回调逻辑即可）
				custom: {},
				openid: "", // 微信公众号需要
				checkboxValue: [],
				// 基本案列数据
				checkboxList: [],
				checkArr: [], // 勾选的报名
				formData: {},
				total: 0,
				list: [], // 已报名数据
				findIndex: '-1',
				isOut: false, // 是否超时
				latitude: '',
				longitude: '',
			}
		},
		onLoad(option) {
			this.id = option.id
		},
		onShow() {
			this.getList()
		},
		onShareAppMessage(res) {
			return {
				title: this.formData.title,
				path: '/pages/competition/detail?id=' + this.id,
				imageUrl: this.formData.photo_url
			}
		},
		// 自定义页面的分享到朋友圈
		onShareTimeline(res) {
			return {
				title: this.formData.title,
				path: '/pages/competition/detail?id=' + this.id,
				imageUrl: this.formData.photo_url
			}
		},
		methods: {
			// 获取总订单，查找对比
			getList() {
				uniCloud.callFunction({
					name: 'order',
					data: {
						dbName: 'order',
						type: 'get',
						pageIndex: 1,
						pageSize: 20,
						filter: {
							status: 1,
							openId: uni.getStorageSync('openid')
						}
					},
					success: res => {
						this.list = res.result.data
						this.getDetail()
					}
				})
			},
			// 获取详情
			getDetail() {
				uni.showLoading({
					title: '加载中'
				})
				uniCloud.callFunction({
					name: 'getDetail',
					data: {
						dbName: 'competition',
						type: 'detail',
						id: this.id
					},
					success: res => {
						this.formData = res.result.data
						let index = this.list.findIndex(item => item.goodsId == this.formData._id)
						if (new Date().getTime() > new Date(this.formData.end_time).getTime()) {
							this.isOut = true
						} else {
							this.isOut = false
						}
						let address = this.formData.address + this.formData.detailAddress
						uni.request({
							url: 'https://api.map.baidu.com/geocoding/v3/?address=' + address +
								'&output=json&ak=46Rj4lQ87uTS5h15ppDmEBUzF823Lwz0',
							dataType: "jsonp",
							success: Res => {
								console.log('地址', JSON.parse(Res.data))
								this.latitude = JSON.parse(Res.data).result.location.lat
								this.longitude = JSON.parse(Res.data).result.location.lng
							}
						})
						console.log('index', index)
						this.findIndex = index
						this.total = this.formData.basicrate
						uni.hideLoading()
					},
					fail: err => {
						uni.hideLoading()
						uni.showToast({
							title: '查询失败！',
							icon: 'none'
						})
					}
				})
			},
			// 打开地图
			toMap() {
				uni.openLocation({
					latitude: Number(this.latitude),
					longitude: Number(this.longitude),
					address: this.formData.address,
					name: this.formData.title,
					success: function() {}
				});
			},
			// 拨打电话
			callPhone() {
				uni.makePhoneCall({
					phoneNumber: this.formData.phone //仅为示例
				});
			},
			// 选择其他费用
			changeGroup(e) {
				console.log(e)
				let total = 0
				let checkArr = []
				this.formData.otherArr.forEach(item => {
					e.forEach(items => {
						if (item.value == items) {
							total += Number(item.price)
							let obj = {
								id: item.value,
								name: item.text,
								price: item.price
							}
							checkArr.push(obj)
						}
					})
				})
				this.checkArr = checkArr
				console.log('ttoa', total)
				this.total = Number(this.formData.basicrate) + total
			},
			async pay() {
				if (!uni.getStorageSync('isLogin')) {
					uni.showToast({
						title: '请先登录！',
						icon: 'none'
					})
					return
				}
				if (Number(this.formData.peopleNum) === this.formData.enrollment) {
					uni.showToast({
						title: '报名人数上限了！',
						icon: 'none'
					})
					return
				}
				if (this.findIndex != '-1') {
					return
				}
				let timeCha = uni.$uv.timeFrom(new Date(uni.getStorageSync('userInfo').birthday).getTime(), false)
				let numberYear = 0
				let uLevel = ''
				if (timeCha.indexOf('年') != -1) {
					numberYear = timeCha.split('年')[0]
				} else {
					numberYear = timeCha.split('个')[0] * 0.1
				}
				if (Number(numberYear) > 6 && Number(numberYear) < 8) {
					uLevel = 6
				} else if (Number(numberYear) >= 8 && Number(numberYear) < 10) {
					uLevel = 8
				} else if (Number(numberYear) >= 10 && Number(numberYear) < 12) {
					uLevel = 10
				} else if (Number(numberYear) >= 12 && Number(numberYear) < 14) {
					uLevel = 12
				} else if (Number(numberYear) >= 14 && Number(numberYear) < 16) {
					uLevel = 14
				} else {
					uLevel = 0
				}
				uni.showLoading({
					title: '支付中111...'
				})
				let obj = {
					openId: uni.getStorageSync('openid'),
					compId: this.formData._id,
					checkArr: this.checkArr,
					uLevel: uLevel,
					compName: this.formData.title,
					photo_url: this.formData.photo_url,
					create_time: this.formData.create_time,
					username: uni.getStorageSync('userInfo').nickName,
					userPhone: uni.getStorageSync('userInfo').phone
				}
				this.custom = obj
				this.order_no = `test` + Date.now(); // 模拟生成订单号
				this.out_trade_no = `${this.order_no}-1`; // 模拟生成插件支付单号
				// 发起支付
				this.$refs.pay.createOrder({
					provider: 'wxpay', // 支付供应商
					total_fee: Number(this.total) * 100, // 支付金额，单位分 100 = 1元
					order_no: this.order_no, // 业务系统订单号（即你自己业务系统的订单表的订单号）
					out_trade_no: this.out_trade_no, // 插件支付单号
					description: this.description, // 支付描述
					type: this.type, // 支付回调类型
					qr_code: this.qr_code, // 是否强制使用扫码支付
					openid: this.openid, // 微信公众号需要
					custom: this.custom, // 自定义数据
				});
				// setTimeout(() => {
				// 	uni.hideLoading()
				// 	uni.showToast({
				// 		title: '支付成功！',
				// 		icon: 'success'
				// 	})
				// }, 2000)
			},
			// 监听事件 - 支付订单创建成功（此时用户还未支付）
			onCreate(res) {
				console.log('create: ', res);
				// 如果只是想生成支付二维码，不需要组件自带的弹窗，则在这里可以获取到支付二维码 qr_code_image
			},
			// 监听事件 - 支付成功
			onSuccess(res) {
				console.log('success: ', res);

				if (res.has_paid) {
					// 代表用户已付款，且你自己写的回调成功并正确执行了
					let obj = {
						status: res.pay_order.status,
						pay_date: res.pay_order.pay_date,
						username: res.pay_order.custom.username,
						userphone: res.pay_order.custom.userPhone,
						userAge: uni.getStorageSync('userInfo').birthday,
						sex: uni.getStorageSync('userInfo').sex,
						goodsId: res.pay_order.custom.compId,
						goodsTime: res.pay_order.custom.create_time,
						goodsCheck: res.pay_order.custom.checkArr,
						photo_url: res.pay_order.custom.photo_url,
						openId: res.pay_order.custom.openId,
						goodsName: res.pay_order.custom.compName,
						uLevel: res.pay_order.custom.uLevel,
						orderNo: res.pay_order.order_no,
						outTradeNo: res.pay_order.out_trade_no,
						totalFee: res.pay_order.total_fee
					}
					uniCloud.callFunction({
						name: 'order',
						data: {
							dbName: 'order',
							type: 'add',
							orderInfo: obj
						}
					})
					uniCloud.callFunction({
						name: 'enrollment',
						data: {
							id: this.formData._id,
							type: 'update',
							dbName: 'competition',
							typeAction: 'add'
						},
						success: res => {
							console.log('成功', res)
						}
					})
				} else {
					// 代表用户已付款，但你自己写的回调执行失败（通常是因为你的回调代码有问题）
					console.log()
				}
			},
			onFail(err) {
				console.log('err: ', err)

			},
			// 查询订单状态
			async getOrder() {
				uni.showLoading({
					title: '测试中'
				})
				let res = await this.$refs.pay.getOrder({
					out_trade_no: this.out_trade_no, // 插件支付单号
					await_notify: true
				});
				if (res) {
					let obj = {
						"-1": "已关闭",
						"1": "已支付",
						"0": "未支付",
						"2": "已部分退款",
						"3": "已全额退款"
					};
					uni.showToast({
						title: obj[res.status] || res.errMsg,
						icon: "none"
					});
				}
			},
			// 发起退款
			async refund() {

			},
		}
	}
</script>

<style lang="scss" scoped>
	.box {
		padding: 20rpx 30rpx;

		.title {
			font-size: 34rpx;
			font-weight: bold;
			padding: 10rpx 0;
		}



		.item {
			margin: 20rpx 0;
			display: flex;
			align-items: center;
			font-weight: 500;

			.titles {
				font-size: 28rpx;
				color: #909399;
				width: 30%;
			}

			.values {
				font-weight: 500;
				font-size: 26rpx;
				margin-top: 6rpx;
			}
		}
	}

	.boxs {

		.title {
			font-size: 34rpx;
			font-weight: bold;
			padding: 10rpx 30rpx;
			padding-bottom: 30rpx;
			border-bottom: 1px solid #f4f4f5;
		}

		.infos {
			font-size: 28rpx;
			padding: 20rpx 30rpx;
		}
	}

	.line {
		height: 10rpx;
		background-color: #f4f4f5;
		width: 100%;
		margin: 20rpx 0;
	}

	.checkx {
		.title {
			font-size: 34rpx;
			font-weight: bold;
			padding: 10rpx 30rpx;
			padding-bottom: 30rpx;
			border-bottom: 1px solid #f4f4f5;
		}

		.checkeds {
			padding: 10rpx 30rpx;
		}
	}

	.footer {
		position: fixed;
		bottom: 0;
		width: 100%;
		height: 140rpx;
		background-color: #fff;
		z-index: 9999;
		border-top: 1px solid #f4f4f5;
		display: flex;
		align-items: center;

		.left {
			flex: 1;

			.phones {
				background-color: #f3f2f7;
				border-radius: 50rpx;
				padding: 10rpx;
				width: fit-content;
				margin-left: 20%;
			}
		}

		.center {
			flex: 2;
			margin-right: 5%;

			.btn {
				background-color: #ff9900;
				color: #fff;
				border-radius: 50rpx;
				height: 80rpx;
				line-height: 80rpx;
				width: 100%;
				margin: 30rpx auto;
				text-align: center;
			}
		}

		.right {
			flex: 2;
			text-align: right;
			padding-right: 10rpx;
			display: flex;
			align-items: center;
		}

	}
</style>